package com.zzyl.nursing.service.impl;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

/**
 * 设备表Service业务层处理
 *
 * @author qqq
 * @date 2025-01-04
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        queryProductListRequest.setPageSize(200);
        queryProductListRequest.setCurrentPage(1);
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductListResponse queryProductListResponse = null;
        try {
            queryProductListResponse = client.queryProductList(queryProductListRequest);
            if (queryProductListResponse.getBody().success) {
                String jsonStr = JSONUtil.toJsonStr(queryProductListResponse.getBody().getData().getList().getProductInfo());
                stringRedisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, jsonStr);
                return;
            }
        } catch (Exception e) {
            log.error("同步阿里云平台产品列表失败", e);
        }
        throw new ServiceException("同步阿里云平台产品列表失败");
    }

    /**
     * 查询所有的产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProducts() {
        String jsonStr = stringRedisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        if (StrUtil.isEmpty(jsonStr)) {
            throw new ServiceException("请先同步产品数据!");
        }
        List<ProductVo> productVoList = JSONUtil.toList(jsonStr, ProductVo.class);
        return productVoList;
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        // 判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        long count = count(queryWrapper);
        if(count > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }
        // 保存设备到iot平台
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

        // 判断保存设备到iot平台是否成功
        if(!response.getBody().success) {
            throw new RuntimeException(response.getBody().getErrorMessage());
        }

        // 查询产品数据
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setProductKey(deviceDto.getProductKey());
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductResponse queryProductResponse;
        try {
            queryProductResponse = client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        // 判断接口是否调通
        if(!queryProductResponse.getBody().success) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }

        // 设置产品名称到设备对象
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setProductName(queryProductResponse.getBody().getData().productName);

        // 物理位置
        if(device.getLocationType().equals(0)) {
            device.setPhysicalLocationType(-1);
        }

        // 补全设备id
        device.setIotId(response.getBody().getData().getIotId());

        try {
            deviceMapper.insertDevice(device);
        } catch (Exception e) {
            // 删除iot中的设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setDeviceName(device.getDeviceName());
            deleteDeviceRequest.setProductKey(device.getProductKey());
            deleteDeviceRequest.setIotId(device.getIotId());
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            try {
                client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new BaseException("物联网接口 - 删除设备，调用失败");
            }
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
    }

    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //1. 数据的
        Device device = lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()).one();
        DeviceVo vo = BeanUtil.toBean(device, DeviceVo.class);
        //2. Iot平台上的
        setIotDeviceDetail(vo);
        return vo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param request
     * @return
     */
    @Override
    public R queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        try {
            QueryThingModelPublishedResponse queryThingModelPublishedResponse = client.queryThingModelPublished(request);
            if (queryThingModelPublishedResponse.getBody().success) {
                return R.ok(queryThingModelPublishedResponse.getBody().getData());
            }
        } catch (Exception e) {
            log.error("查询产品的物模型数据失败", e);
        }
        throw new RuntimeException("查询产品的物模型数据失败");
    }

    /**
     * 查询设备最新数据
     *
     * @param request
     * @return
     */
    @Override
    public R queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        try {
            QueryDevicePropertyStatusResponse queryDevicePropertyStatusResponse = client.queryDevicePropertyStatus(request);
            if (queryDevicePropertyStatusResponse.getBody().success) {
                return R.ok(queryDevicePropertyStatusResponse.getBody().getData());
            }
        } catch (Exception e) {
            log.info("查询设备最新数据失败", e);
        }
        throw new ServiceException("查询设备最新数据失败");
    }

    /**
     * 设置iot平台上的设备信息
     *
     * @param vo
     */
    private void setIotDeviceDetail(DeviceVo vo) {
        QueryDeviceDetailRequest deviceDetailRequest = new QueryDeviceDetailRequest();
        deviceDetailRequest.setProductKey(vo.getProductKey());
        deviceDetailRequest.setIotId(vo.getIotId());
        deviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        try {
            QueryDeviceDetailResponse queryDeviceDetailResponse = client.queryDeviceDetail(deviceDetailRequest);
            if (queryDeviceDetailResponse.getBody().success) {
                BeanUtil.copyProperties(queryDeviceDetailResponse.getBody().getData(), vo);
            }
        } catch (Exception e) {
            log.error("查询Iot设备详情失败", e);
            throw new ServiceException("查询Iot设备详情失败");
        }
    }

//    /**
//     * 删除IOT平台上的设备
//     *
//     * @param device
//     */
//    private void deleteIotDevice(Device device) {
//        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
//        deleteDeviceRequest.setProductKey(device.getProductKey());
//        deleteDeviceRequest.setIotId(device.getIotId());
//        deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
//
//        try {
//            DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(deleteDeviceRequest);
//            if (deleteDeviceResponse.getBody().success) {
//                return;
//            }
//        } catch (Exception e) {
//            log.error("删除Iot平台设备失败!", e);
//        }
//        throw new ServiceException("删除Iot平台设备失败!");
//    }
//
//    /**
//     * 设置产品的名称
//     *
//     * @param device
//     */
//    private void setProductName(Device device) {
//        List<ProductVo> productVos = allProducts();
//        productVos.stream().filter(p -> ObjectUtil.equal(device.getProductKey(), p.getProductKey()))
//                .findFirst()
//                .ifPresent(vo -> device.setProductName(vo.getProductName()));
//    }
//
//    /**
//     * IOT新增设备
//     *
//     * @param deviceDto
//     * @return
//     */
//    private String addIotDevice(DeviceDto deviceDto) {
//        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
//        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
//        try {
//            RegisterDeviceResponse registerDeviceResponse = client.registerDevice(registerDeviceRequest);
//            if (registerDeviceResponse.getBody().success) {
//                String iotId = registerDeviceResponse.getBody().getData().getIotId();
//                log.info("新增的设备{}, iotId={}", deviceDto.getDeviceName(), iotId);
//                return iotId;
//            }
//        } catch (Exception e) {
//            log.error("IOT新增设备失败", e);
//        }
//        throw new ServiceException("IOT新增设备失败");
//    }
}